package utils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/code")
public class VerifyCode extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final int WIDTH = 120;
    private static final int HEIGHT = 30;
    private static final int CODE_LENGTH = 4;
    private static final int INTERFERENCE_LINES = 5;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应头，禁止缓存
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 创建图像缓冲区
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 设置背景色
        g.setColor(getRandomColor(200, 250));
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 设置字体
        g.setFont(new Font("Arial", Font.BOLD, 24));

        // 画边框
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);

        // 生成随机验证码
        Random random = new Random();
        StringBuilder code = new StringBuilder();

        // 可选字符集（字母、数字）
        String chars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";

        for (int i = 0; i < CODE_LENGTH; i++) {
            char c = chars.charAt(random.nextInt(chars.length()));
            code.append(c);

            // 设置随机颜色
            g.setColor(getRandomColor(20, 130));

            // 添加随机旋转角度
            double angle = random.nextDouble() * 0.2 - 0.1; // -0.1到0.1弧度
            g.rotate(angle, i * (WIDTH / CODE_LENGTH) + 15, HEIGHT / 2);

            // 绘制字符
            g.drawString(String.valueOf(c), i * (WIDTH / CODE_LENGTH) + 10, HEIGHT - 5);

            // 恢复旋转
            g.rotate(-angle, i * (WIDTH / CODE_LENGTH) + 15, HEIGHT / 2);
        }

        // 添加干扰线
        for (int i = 0; i < INTERFERENCE_LINES; i++) {
            g.setColor(getRandomColor(100, 200));
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }

        // 添加噪点
        for (int i = 0; i < 100; i++) {
            int x = random.nextInt(WIDTH);
            int y = random.nextInt(HEIGHT);
            image.setRGB(x, y, getRandomColor(0, 255).getRGB());
        }

        // 将验证码存入Session
        HttpSession session = request.getSession();
        session.setAttribute("code", code.toString());
        System.out.println("生成的验证码: " + code);

        // 输出图像
        ImageIO.write(image, "JPEG", response.getOutputStream());

        // 释放资源
        g.dispose();
    }

    // 生成随机颜色
    private Color getRandomColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) fc = 255;
        if (bc > 255) bc = 255;

        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);

        return new Color(r, g, b);
    }
}